//
// Created by mmuee on 2024/5/8.
//

#ifndef YWZM_THREADSAFEQUEUE_HPP
#define YWZM_THREADSAFEQUEUE_HPP

#include "ConstDefine.hpp"
#include <queue>

template<typename T>
class ThreadSafeQueue
{
private:
    mutable std::mutex mut{};
    mutable std::condition_variable data_cond{};
    using queue_type = std::queue<T>;
    queue_type data_queue{};
    mutable std::atomic<bool> isQuit{false};

public:
    using value_type = typename queue_type::value_type;
    using container_type = typename queue_type::container_type;
    ThreadSafeQueue() = default;
    ThreadSafeQueue(const ThreadSafeQueue&) = delete;
    ThreadSafeQueue& operator=(const ThreadSafeQueue&) = delete;
    /*
     * 使用迭代器为参数的构造函数,适用所有容器对象
     * */
    template<typename InputIterator>
    ThreadSafeQueue(InputIterator first, InputIterator last)
    {
        for (auto itor = first; itor != last; ++itor)
        {
            data_queue.push(*itor);
        }
    }
    explicit ThreadSafeQueue(const container_type& c) : data_queue(c) {}

    /* 使用初始化列表为参数的构造函数 */
    ThreadSafeQueue(std::initializer_list<value_type> list) : ThreadSafeQueue(list.begin(), list.end()) {}

    /* 将元素加入队列 */
    void push(const value_type& new_value)
    {
        std::lock_guard<std::mutex> locker(mut);
        data_queue.push(std::move(new_value));
        data_cond.notify_one();
    }

    /* 从队列中弹出一个元素,如果队列为空就阻塞 */
    bool waitPop(value_type& v)
    {
        std::unique_lock<std::mutex> locker(mut);
        data_cond.wait(locker, [this] { return !this->data_queue.empty() || isQuit; });
        v = std::move(data_queue.front());
        data_queue.pop();
        return !isQuit;
    }

    /* 从队列中弹出一个元素,如果队列为空返回false */
    bool tryPop(value_type& value)
    {
        std::lock_guard<std::mutex> locker(mut);
        if (data_queue.empty())
            return false;
        value = std::move(data_queue.front());
        data_queue.pop();
        return true;
    }

    auto empty() const -> decltype(data_queue.empty())
    {
        std::lock_guard<std::mutex> locker(mut);
        return data_queue.empty();
    }

    auto size() const -> decltype(data_queue.size())
    {
        std::lock_guard<std::mutex> locker(mut);
        return data_queue.size();
    }
    void quit()
    {

        std::lock_guard<std::mutex> locker(mut);
        isQuit = true;
        data_cond.notify_one();
    }
};

#endif //YWZM_THREADSAFEQUEUE_HPP
